package com.itpeng.mobile;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itpeng.constant.MessageConstant;
import com.itpeng.constant.RedisMessageConstant;
import com.itpeng.entity.Result;
import com.itpeng.exception.HealthException;
import com.itpeng.pojo.Member;
import com.itpeng.pojo.Order;
import com.itpeng.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * @Aythor:彭彦钦
 * @Data: 2020/9/26  21:33
 */
@RestController
@RequestMapping("/login")
public class LoginmobileController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    /**
     * 校验用户名和密码
     * @param loginInfo
     * @param response
     * @return
     */
    @PostMapping("/check")
    public Result checkMember(@RequestBody Map<String, String> loginInfo, HttpServletResponse response){
        String telephone = loginInfo.get("telephone");
        String key = RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone;
        //从redis中查询验证码，与用户输入的验证码进行匹配
        Jedis jedis = jedisPool.getResource();
        String codeInRedis = jedis.get(key);
        //判断用户有没有发送验证码
        if (StringUtils.isEmpty(codeInRedis)){
            return new Result(false, "验证码已超时或未发送，请重新获取验证码");
        }
        //匹配验证码是否一致
        if (!codeInRedis.equals(loginInfo.get("validateCode"))){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        jedis.del(key);
        //从数据库中查询该手机号是否已经注册过会员
        Member member = memberService.findByTelephone(telephone);
        //若member为空则代表该手机号为注册过会员，则为其注册为会员
        if (member == null){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member.setRemark("手机号快速登录注册");
            member.setPassword("123456");
            memberService.add(member);
        }

        //若已经注册过会员，或添加成为会员后，则将会员信息存储在session中，跟踪用户
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setMaxAge(30*24*60*60);//存储时间为一个月
        cookie.setPath("/");// 访问的路径 根路径下时 网站的所有路径 都会发送这个cookie

        //将cookie存储起来一起发送给前端
        response.addCookie(cookie);

        return new Result(true, MessageConstant.LOGIN_SUCCESS);

    }

}
